﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers
{
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;

    internal class UserAgentParser
    {
        private static List<ReplaceFilter> _replaceFilters = new List<ReplaceFilter>();

        private static void InitReplaceFilters()
        {
            lock (_replaceFilters)
            {
                if (_replaceFilters.Count == 0)
                {
                    _replaceFilters.Add(new ReplaceFilter(@"UP.Link/[\d.]+", ""));
                    _replaceFilters.Add(new ReplaceFilter(@"/IMEI/SN[\d|X]+", ""));
                    _replaceFilters.Add(new ReplaceFilter(@"^\s+|\s+$", ""));
                }
            }
        }

        internal static string Parse(string userAgent)
        {
            InitReplaceFilters();
            foreach (ReplaceFilter filter in _replaceFilters)
            {
                userAgent = filter.ParseString(userAgent);
            }
            return userAgent;
        }

        private class ReplaceFilter
        {
            private Regex _regex;
            private string _replacement;

            internal ReplaceFilter(string expression, string replacement)
            {
                this._regex = new Regex(expression, RegexOptions.Compiled);
                this._replacement = replacement;
            }

            internal string ParseString(string useragent)
            {
                return this._regex.Replace(useragent, this._replacement);
            }
        }
    }
}

